import vm from "@/main.js"
let QQMapWX = require('@/utils/qqmap-wx-jssdk.min.js');
let $mqtt = require('@/utils/mqtt.min.js')

import {
	getStoreSyncUtil
} from "@/utils/store.js"
import {
	dataPointMqttTopic,
	fenceMqttTopic,
	unReadNumTopic,
	authTopic,
	mqttUrl,
	mqttUserName,
	mqttUserPassword,
	baiduUrl,
	tencentAK,
	baiduAK
} from '@/api/http/setting';



import {
	getCarDetailAPI
} from "@/api/api/car.js"


//获取日期
export const getDate = (date = "") => {
	if (date == "") {
		date = new Date();
	}
	let year = date.getFullYear();
	let month = date.getMonth() + 1;
	let newMonth = month < 10 ? "0" + month : month;
	let day = date.getDate();
	let newDay = day < 10 ? "0" + day : day;

	return year + "-" + newMonth + "-" + newDay;
};
//点击节流事件，防止重复点击事件
export const throttle = function(fn, gapTime) {
	if (gapTime == null || gapTime == undefined) {
		gapTime = 1000
	}
	let _lastTime = null
	// 返回新的函数
	return function() {
		let _nowTime = +new Date()
		if (_nowTime - _lastTime > gapTime || !_lastTime) {
			fn.apply(this, arguments) //将this和参数传给原函数
			_lastTime = _nowTime
		}
	}
}

export const getSecondsUtil = (time) => {
	var date = new Date(time);
	var y = date.getFullYear();
	let month = date.getMonth() + 1;
	var nmonth = (month < 10 ? '0' + month : month);
	var day = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
	var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours());
	var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
	var s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
	var strDate = y + "-" + nmonth + "-" + day + " " + h + ":" + m + ":" + s;
	return strDate;
};

//获取当前时间时分秒，毫秒
export const getNowTime = function() {
	let date = new Date();
	let year = date.getFullYear();
	let month = date.getMonth() + 1;
	let month2 = month < 10 ? "0" + month : month;
	let date2 = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
	let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
	let minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
	let second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
	let milliSeconds = date.getMilliseconds();
	let currentTime = year + '-' + month2 + '-' + date2 + ' ' + hour + ':' + minute + ':' + second;
	return currentTime;
}



export const timeago = (dateTimeStamp) => {
	//console.log('dateTimeStamp',dateTimeStamp)
	var minute = 1000 * 60; //把分，时，天，周，半个月，一个月用毫秒表示
	var hour = minute * 60;
	var day = hour * 24;
	var week = day * 7;
	var halfamonth = day * 15;
	var month = day * 30;
	var now = new Date().getTime(); //获取当前时间毫秒
	let result = '';
	if (dateTimeStamp == '') {
		return '刚刚';
	}
	var diffValue = now - dateTimeStamp; //时间差

	if (diffValue < 0) {
		return;
	}
	var minC = diffValue / minute; //计算时间差的分，时，天，周，月
	var hourC = diffValue / hour;
	var dayC = diffValue / day;
	var weekC = diffValue / week;
	var monthC = diffValue / month;
	if (monthC >= 1 && monthC <= 3) {
		result = " " + parseInt(monthC) + "月前"
	} else if (weekC >= 1 && weekC <= 3) {
		result = " " + parseInt(weekC) + "周前"
	} else if (dayC >= 1 && dayC <= 6) {
		result = " " + parseInt(dayC) + "天前"
	} else if (hourC >= 1 && hourC <= 23) {
		result = " " + parseInt(hourC) + "小时前"
	} else if (minC >= 1 && minC <= 59) {
		result = " " + parseInt(minC) + "分钟前"
	} else if (diffValue >= 0 && diffValue <= minute) {
		result = "刚刚"
	} else {
		var datetime = new Date();
		datetime.setTime(dateTimeStamp);
		var Nyear = datetime.getFullYear();
		var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
		var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
		var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
		var Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
		var Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
		result = Nyear + "-" + Nmonth + "-" + Ndate
	}
	//console.log('result',result);
	return result;
}

export const $currentRoute = () => {
	let currentRoutes = getCurrentPages(); // 获取当前打开过的页面路由数组
	let currentRoute = currentRoutes[currentRoutes.length - 1].route //获取当前页面路由
	return currentRoute;
}
export let client;

export const mqttMSG = () => {
	let deviceData = vm.$store.state.deviceData;
	const connectUrl = mqttUrl;
	// #ifdef H5
	client = $mqtt.connect('wss://' + connectUrl, {
		username: mqttUserName,
		password: mqttUserPassword,
		//clientId:'mqttjs_'+deviceData.ecuId, //clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8)
		clean: true, //clean 设置为false，是为了让客户端掉线的时候，服务器必须在客户端断开之后继续存储/保持客户端的订阅状态。即当为true的时候，如果掉线了，服务端会清理链接状态的数据和内容。当为false的时候，服务端会保存消息发送期间，链接断开导致发送失败的消息。这样连上的时候就会自动推送到订阅的客户端。
		keepAlive: 0, //（1） 配置项里的 keepAlive 指的是心跳时间。以秒为单位。定义服务端从客户端接收到消息的最大间隔时间。可以设置为0，表示客户端一直不断开，除非主动断开。
	});

	// #endif

	// let clientId = 'mqttjs_' + deviceData.ecuId.toString(16).substr(3);
	// console.log("clientId", clientId);
	// #ifdef MP-WEIXIN 
	client = $mqtt.connect('wxs://' + connectUrl, {
		username: mqttUserName,
		password: mqttUserPassword,
		// clientId:clientId,
		clean: true,
		keepAlive: 0,
	}); //不要写成了wss ，要写成wxs 协议
	// #endif
	if (client.connected) {
		client.end();
	}
	let topicalArr  = [];
	let unReadNum = unReadNumTopic + vm.$store.state.loginUser.user_id;
	topicalArr.push(unReadNum);
	if(!vm.$validatenull(deviceData)){
		let topicalDataPoint = dataPointMqttTopic + deviceData.ecuId; //上报数据推送
		let isCrossFence = fenceMqttTopic + deviceData.ecuId; //电子围栏是否超出区域推送
		let isAuthTopic = authTopic + deviceData.ecuId; //电子围栏是否超出区域推送
		topicalArr.push(topicalDataPoint);
		topicalArr.push(isCrossFence)
		topicalArr.push(isAuthTopic)
	}
	
	
	// mqtt连接
	client.on("connect", e => {
		console.log("mqtt连接成功", e);
		client.subscribe(topicalArr, async error => {
			if (!error) {
				console.log("订阅的成功-mqttMSG" + deviceData.ecuId);
			} else {
				console.log("订阅失败");
			}
		});
	});
	// 接收消息处理
	client.on("message", (topic, message) => {
		let mqttData = message.toString();
		console.log("收到来自", topic, `的消息-${getNowTime()}`, mqttData);
		if (!vm.$validatenull(mqttData)) {
			let data = {};
			if (typeof mqttData == "string") {
				data = JSON.parse(mqttData);
			} else {
				data = mqttData;
			}

			let lastIndex = topic.lastIndexOf("/");
			let name = topic.substring(0, lastIndex + 1);

			if (dataPointMqttTopic == name || fenceMqttTopic == name) {
				let dataPoint = data.dataPoint;
				if (fenceMqttTopic == name) {
					// console.log("收到来自", topic, "的消息",mqttData);
					vm.$store.commit("setMapDataPoint", {
						...vm.$store.state.mapDataPoint,
						upDataType: 0,
						...data,
					});
				} else {
					vm.$store.commit("setMapDataPoint", {
						...vm.$store.state.mapDataPoint,
						carLatitude: dataPoint.carLatitude,
						carLongitude: dataPoint.carLongitude,
						upDataType: 1
					});
					//如果蓝牙连接，则取蓝牙状态，如果没有则取mqtt
					vm.$store.commit("setEnduranceMileage",dataPoint.enduranceMileage);
					if (!vm.isConnected) {
						vm.$store.commit("setIndexDataPoint", {
							keyStatus: dataPoint.keyStatus,
							lastUpFlag: 0,
							engineStatus: dataPoint.engineStatus,
							surplusOil: dataPoint.surplusOil,
							insideVoltage: dataPoint.insideVoltage,
							carFrontTirePressure: dataPoint.carFrontTirePressure,
							carRearTirePressure: dataPoint.carRearTirePressure,
							lockStatus: dataPoint.lockStatus,
							carStatus: dataPoint.carStatus,
						});
						vm.$store.commit("setGuardDataPoint", {
							carStatus: dataPoint.carStatus,
						});
					}



					vm.$store.commit("setDetailDataPoint", {
						surplusOil: dataPoint.surplusOil,
						carFrontTirePressure: dataPoint.carFrontTirePressure,
						carRearTirePressure: dataPoint.carRearTirePressure,
						averageOil: dataPoint.averageOil,
						insideVoltage: dataPoint.insideVoltage,
						meterMileage: dataPoint.meterMileage
					});

					vm.$store.commit("setOdometerDataPoint", {
						meterMileage: dataPoint.meterMileage,
						averageSpeed: dataPoint.averageSpeed,
						subtotalMileage1: dataPoint.subtotalMileage1,
						subtotalMileage2: dataPoint.subtotalMileage2
					});

					
					if (!vm.isConnected) {
						vm.$store.commit("setDrivingDataPoint", {
							currentOil: dataPoint.currentOil,
							engineSpeed: dataPoint.engineSpeed,
							engineTemperature: dataPoint.engineTemperature,
							doorOpen: dataPoint.doorOpen,
							driveAverageOil: dataPoint.driveAverageOil,
							carFrontTirePressure: dataPoint.carFrontTirePressure,
							carRearTirePressure: dataPoint.carRearTirePressure,
							createTime: data.createTime,
							carSpeed: dataPoint.carSpeed
						});
					} 

				}


			}

			if (unReadNumTopic == name) {
				vm.$store.commit("setUnReadNum", data.unReadNum);
			}
			if (authTopic == name) {
				vm.$store.commit("setDeviceData", {
					...vm.$store.state.deviceData,
					authTime:data.authTime,
					isAuth:data.isAuth,
				}
				);
			}
		}
	});

	// 断开发起重连
	client.on("reconnect", error => {
		console.log("正在重连:", error);
	});
	// 链接异常处理
	client.on("error", error => {
		console.log("mqtt连接失败:", error);
	});
}

let qqmapsdk = null;
export const reverseGeocoderToAddress = (latitude, longitude, callback = () => {}) => {
	if (vm.$validatenull(qqmapsdk)) {
		qqmapsdk = new QQMapWX({
			key: tencentAK
		});
	}
	qqmapsdk.reverseGeocoder({
		location: {
			latitude: latitude,
			longitude: longitude
		},
		success(res) {
			console.log("success",res);
			callback(res);
		},
		fail(res) {
			console.log("fail",res);
		}
	})
}


export const $getCarDetail = (id, callback = () => {}) => {
	getCarDetailAPI(id).then(([err1, deviceData2]) => {
		if (err1) return;
		let newDeviceData = {};
		for (let i = 0; i < deviceData2.deviceDatapointVOList.length; i++) {
			let item = deviceData2.deviceDatapointVOList[i];
			if (item.pointName == "carLatitude" || item.pointName == "carLongitude") {
				newDeviceData[item.pointName] = Number(item.pointValue); //转化成数值
			} else {
				newDeviceData[item.pointName] = Number(item.pointRealValue); //转化成数值
			}

		}
		//deviceData2.tboxExpireTime = "2023-3-13 00:00:00"
		let deviceData = {
			carPhotoLink: deviceData2.carPhotoLink,
			id: deviceData2.id,
			carElectronicFence: deviceData2.carElectronicFence,
			carTypeName: deviceData2.carTypeName,
			carTypeId: deviceData2.carTypeId,
			ecuId: deviceData2.ecuId,
			status: deviceData2.status,
			nickName: deviceData2.nickName,
			licensePlateNumber: deviceData2.licensePlateNumber,
			isAuth: deviceData2.isAuth,
			engineNum: deviceData2.engineNum,
			colorName: deviceData2.colorName,
			createTime: deviceData2.createTime,
			vin: deviceData2.vin,
			authTime: deviceData2.authTime,
			lastUpFlag: deviceData2.lastUpFlag,
			tboxExpireTime:deviceData2.tboxExpireTime

		}
		vm.$store.commit("setDeviceData", deviceData)
		vm.$store.commit("setEnduranceMileage",newDeviceData.enduranceMileage);

		vm.$store.commit("setMapDataPoint", {
			isCrossFence: deviceData2.isCrossFence,
			carLatitude: newDeviceData.carLatitude,
			carLongitude: newDeviceData.carLongitude,
			upDataType: 1
		});

		//newDeviceData.surplusOil = 21;
		// lockStatus=车锁状态，0关1开		// key_status=车钥匙状态，0关 1开		// engineStatus=发动机状态（0=关闭，1=开启）
		let lastUpFlag = deviceData2.lastUpFlag;
		
		vm.$store.commit("setIndexDataPoint", {
			keyStatus: lastUpFlag == 0 ? newDeviceData.keyStatus : 0,//如果是离线状态，需要改变值
			lastUpFlag: deviceData2.lastUpFlag,
			engineStatus: lastUpFlag == 0 ? newDeviceData.engineStatus :0,//如果是离线状态，需要改变值
			surplusOil: newDeviceData.surplusOil,
			insideVoltage: newDeviceData.insideVoltage,
			carFrontTirePressure: newDeviceData.carFrontTirePressure,
			carRearTirePressure: newDeviceData.carRearTirePressure,
			lockStatus: lastUpFlag == 0 ? newDeviceData.lockStatus :0 ,//如果是离线状态，需要改变值
			carStatus: newDeviceData.carStatus,
		});

		vm.$store.commit("setDetailDataPoint", {
			surplusOil: newDeviceData.surplusOil,
			carFrontTirePressure: newDeviceData.carFrontTirePressure,
			carRearTirePressure: newDeviceData.carRearTirePressure,
			averageOil: newDeviceData.averageOil,
			insideVoltage: newDeviceData.insideVoltage,
			meterMileage: newDeviceData.meterMileage
		});

		vm.$store.commit("setOdometerDataPoint", {
			meterMileage: newDeviceData.meterMileage,
			averageSpeed: newDeviceData.averageSpeed,
			subtotalMileage1: newDeviceData.subtotalMileage1,
			subtotalMileage2: newDeviceData.subtotalMileage2
		});

		vm.$store.commit("setGuardDataPoint", {
			carStatus: newDeviceData.carStatus,
		});

		vm.$store.commit("setDrivingDataPoint", {
			currentOil: newDeviceData.currentOil,
			engineSpeed: newDeviceData.engineSpeed,
			engineTemperature: newDeviceData.engineTemperature,
			doorOpen: newDeviceData.doorOpen,
			driveAverageOil: newDeviceData.driveAverageOil,
			carSpeed: newDeviceData.carSpeed,
			carFrontTirePressure: newDeviceData.carFrontTirePressure,
			carRearTirePressure: newDeviceData.carRearTirePressure,
			createTime: deviceData2.deviceDatapointVOList[0].createTime,
		});

		console.log("deviceData", vm.$store.state.deviceData);
		console.log("dataPoint", newDeviceData);
		callback(deviceData);
		if (!vm.$validatenull(newDeviceData.carLatitude) && !vm
			.$validatenull(newDeviceData.carLongitude)) {
			// reverseGeocoderToAddress('39.989494', '116.385297', (res) => {
			reverseGeocoderToAddress(newDeviceData.carLatitude, newDeviceData.carLongitude, (res) => {
				let result = res.result.ad_info;
				let adcode = result.adcode;
				let district = result.district;
				let city = result.city;
				let url = "/baiduApi";
				//#ifdef MP-WEIXIN 
				url = baiduUrl;
				//#endif
				uni.request({
					url: `${url}/weather/v1/?district_id=${adcode}&data_type=fc&ak=${baiduAK}`, //仅为示例，并非真实接口地址。
					success: (weather) => {
						console.log("11111111",weather);
						
						let textDay=weather.data.result.forecasts[0].text_day;
						let weatherTemp={
							city:city,
							district:district,
							textDay:textDay
						};
						if(textDay=="晴"){
							weatherTemp['icon']="qingtian";
							weatherTemp['color']="rgb(255, 153, 51)";
						}else if(["多云","阴"].includes(textDay)){
							weatherTemp['icon']="duoyunyin";
							weatherTemp['color']="rgb(208, 210, 211)";
						}else if(["阵雨","雷阵雨","雷阵雨伴有冰雹","雨夹雪","小雨","中雨","大雨","暴雨","大暴雨","特大暴雨","冻雨","小到中雨","中到大雨","大到暴雨","暴雨到大暴雨","大暴雨到特大暴雨","雨"].includes(textDay)){
							weatherTemp['icon']="yu";
							weatherTemp['color']="rgb(38, 169, 224)";
						}else if(["阵雪","小雪","中雪","大雪","暴雪","小到中雪","中到大雪","大到暴雪","弱高吹雪","雪"].includes(textDay)){
							weatherTemp['icon']="xue";
							weatherTemp['color']="rgb(208, 210, 211)";
						}else if(["雾","浓雾","轻雾","强浓雾","霾","中度霾","重度霾","严重霾","大雾","特强浓雾"].includes(textDay)){
							weatherTemp['icon']="wu";
							weatherTemp['color']="rgb(38, 169, 224)";
						}else if([,"沙尘暴",'浮尘',"扬沙","强沙尘暴"].includes(textDay)){
							weatherTemp['icon']="shachengbao";
							weatherTemp['color']="rgb(255, 153, 51)";
						}else if(textDay=='龙卷风'){
							weatherTemp['icon']="feng";
							weatherTemp['color']="rgb(38, 169, 224)";
						}
						vm.$store.commit("setWeather",weatherTemp)
					}
				});
			})
		}
	});
}

export const getRangeVal = function(val, arr = [5, 10]) {
	if ((!(arr instanceof Array)) || (arr.length > 2) || isNaN(Number(val))) {
		return '';
	}
	if (arr[1] < arr[0]) {
		arr = arr.reverse();
	}
	return uni.$u.test.range(val, arr) ? val : (Number(val) > arr[0] ? arr[1] : arr[0])
}

export const getDifferenceDay=(time1,time2)=>{
	let date1=new Date(time1);
	let date2=time2?new Date(time2):new Date();
	let result = parseInt(date1.getTime()/(1000 * 3600 * 24)) - parseInt(date2.getTime()/(1000 * 3600 * 24));
	console.log("result",result)
	return result;
}





